package com.hspedu.haapy;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class HappyBirthdayHeiGe extends JPanel {

    private static final Color[] colors = {Color.RED, Color.BLUE, Color.GREEN, Color.MAGENTA, Color.ORANGE};
    private final Random random = new Random();
    private int balloonY = 500;
    private Color textColor = Color.RED;
    private boolean candleFlame = true;

    public static void main(String[] args) {
        JFrame frame = new JFrame("生日快乐黑哥！");
        HappyBirthdayHeiGe animation = new HappyBirthdayHeiGe();
        frame.add(animation);
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        // 动画定时器
        Timer timer = new Timer(30, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                animation.balloonY--;
                if (animation.balloonY < -100) {
                    animation.balloonY = 500;
                }

                // 改变文字颜色
                if (System.currentTimeMillis() % 200 < 100) {
                    animation.textColor = colors[animation.random.nextInt(colors.length)];
                }

                // 蜡烛闪烁
                animation.candleFlame = !animation.candleFlame;

                animation.repaint();
            }
        });
        timer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        // 设置背景
        setBackground(new Color(255, 240, 245));

        // 绘制标题
        drawBirthdayText(g);

        // 绘制气球
        drawBalloons(g);

        // 绘制蛋糕
        drawCake(g);
    }

    private void drawBirthdayText(Graphics g) {
        Font font = new Font("微软雅黑", Font.BOLD, 40);
        g.setFont(font);

        // 闪烁文字
        g.setColor(textColor);
        String text = "黑哥生日快乐！";
        FontMetrics fm = g.getFontMetrics();
        int x = (getWidth() - fm.stringWidth(text)) / 2;
        g.drawString(text, x, 100);
    }

    private void drawBalloons(Graphics g) {
        int[] balloonX = {100, 200, 300, 400, 500, 600};
        for (int x : balloonX) {
            g.setColor(colors[random.nextInt(colors.length)]);
            // 气球
            g.fillOval(x, balloonY, 50, 60);
            // 线
            g.drawLine(x + 25, balloonY + 60, x + 25, balloonY + 100);
        }
    }

    private void drawCake(Graphics g) {
        // 蛋糕底层
        g.setColor(new Color(139, 69, 19));
        g.fillRect(300, 400, 200, 80);

        // 蛋糕顶层
        g.setColor(new Color(245, 222, 179));
        g.fillRect(320, 360, 160, 40);

        // 蜡烛
        g.setColor(Color.YELLOW);
        g.fillRect(370, 320, 10, 40);

        // 火焰
        g.setColor(candleFlame ? Color.ORANGE : Color.YELLOW);
        g.fillOval(365, 310, 20, 20);
    }
}
